package net.flowas.secure;

import net.flowas.secure.entity.User;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

public class DemoRealm extends AuthorizingRealm {
  private static final String CART_PU = "cartPU";

  private EntityManager em;

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    // User user = userDao.findUser(upToken.getUsername());
    String jpql = "select o from User as o where o.email = '" + upToken.getUsername()
        + "' and o.password = '" + new String((char[]) upToken.getCredentials()) + "'";
    User user = (User) em.createQuery(jpql).getSingleResult();
    if (user == null) {
      throw new AuthenticationException("用户名或密码不正确！");
    }
    return new SimpleAccount(user, token.getCredentials(), getName());
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    System.out.println("================================");
    Object shiroUser = principals.getPrimaryPrincipal();
    // User user = userDao.findUserByLoginName(shiroUser.loginName);
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    // info.addRoles(user.getRoleList());
    return info;
  }

  /**
   * 依賴注入的變量.
   * 
   * @param persistenceUnitName 持久化单元名称
   */
  public void setPersistenceUnitName(String persistenceUnitName) {
    if (persistenceUnitName == null) {
      persistenceUnitName = CART_PU;
    }
    em = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager();
  }

}
